package com.distribute.application.api.rest.member;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.MapHelper;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.BindingDistributor;
import com.distribute.framework.model.Distributor;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.UserAddress;

@RestController(value="api.BaseApiController")
public class MemberDotController extends BaseApiController{
	
	/**
	 * 获取最近网点信息
	 * @return
	 */
	@RequestMapping("/api/dot/getLatelyDot.do")
	public @title("获取最近网点信息")  Protocol getLatelyDot(
			@title("品牌编号") Long banrdId,
			@title("地址编号") Long adressId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		UserAddress userAddress=UserAddress.where.id(adressId).get();
		List<BindingDistributor> bindingDistributors=BindingDistributor.where.locations(userAddress.getCityOrigin()).bindingState((short)1).merchant(banrdId).list(10000);
		List<Distributor> distributors=new ArrayList<Distributor>();
		for (BindingDistributor bindingDistributor : bindingDistributors) {
			Distributor dot=Distributor.where.id(bindingDistributor.getDistributor()).get();
			distributors.add(dot);
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("id", 0);
		map.put("value", 1000000);
		if (distributors.size()>0) {
			for (Distributor distributor : distributors) {
				String aString=userAddress.getLatitude()+","+userAddress.getLongitude();
				String bString=distributor.getLatitude()+","+distributor.getLongitude();
				double lj=MapHelper.GetPointDistance(aString, bString);	
				if (lj<Double.valueOf(map.get("value").toString())) {
					map.put("id", distributor.toJSON());
					map.put("value", lj);
				}
			}
		}
		if (!map.get("id").toString().equals("0")) {
			protocol.set("type", 1);
			protocol.set("dot",map.get("id"));
		}else {
			protocol.set("type", 2);
			protocol.set("dot", null);
		}
		return protocol;
	}
}
